package com.freecloud.javabasics.design.single;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 单例：注册式、容器缓存式单利
 * @Author: maomao
 * @Date: 2019-10-30 22:05
 */
public class ContainerSingleton {

    private ContainerSingleton(){}

    private static Map<String,Object> ioc = new ConcurrentHashMap<>();

    public static Object getBean(String className){
        if(ioc.containsKey(className)){
            return ioc.get(className);
        }

        synchronized (ioc){
            if(ioc.containsKey(className)){
                return ioc.get(className);
            }
            Object obj = null;
            try {
                obj = Class.forName(className);
                ioc.put(className,obj);
            }catch (Exception e){
                e.printStackTrace();
            }
            return obj;
        }
    }
}
